package com.itheima.store.controller;

import com.itheima.store.common.ProductConst;
import com.itheima.store.entity.PageBean;
import com.itheima.store.entity.Product;
import com.itheima.store.service.ProductService;
import com.itheima.store.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping("product")
    @ResponseBody
    public Result findAll(String method,String pid,String cid,String currentPage){
        if("getHottestAndNewest".equals(method)){
            List<Product> newestList = productService.findNew();
            List<Product> hottest = productService.findHot();
            Map<String,List<Product>> map = new HashMap<>();
            map.put("newestList",newestList);
            map.put("hottestList",hottest);

            return new Result(Result.SUCCESS,"查询成功",map);
        }
        if("getProductById".equals(method)){
            Product product = productService.getProductById(pid);
            if(product != null){
                return new Result(Result.SUCCESS,"查询成功",product);
            }
            return new Result(Result.FAILS,"查询失败");
        }
        if ("getProductByPage".equals(method)){

            if (currentPage == null || "null".equals(currentPage)){
                currentPage =  "1";
            }
            // 调用业务层，获取PageBean对象
            //PageBean pageBean = productService.findByPage(cid,Integer.parseInt(currentPage), ProductConst.PAGE_SIZE);
            // 响应前端
            PageBean pageBean  = productService.getPageInfo(cid,Integer.parseInt(currentPage),ProductConst.PAGE_SIZE);
            if(pageBean != null){
               return  new Result(Result.SUCCESS,"查询成功",pageBean);
            }else{
                return  new Result(Result.FAILS,"查询失败");
            }
        }

        return null;
    }
}
